<!--
 @description 商品列列表(系列和空间)
 @fileName index.vue
 @author zengqiongying
 @created 2023/01/02 16:00:46
-->
<template>
  <div class="goods-list-page" :style="{'padding-top':topHeight+'px'}">
    <div ref="top" class="goods-list-page-head">
      <MineHeader arrow :title="pageTitle" show-statusbar :font-black="false" bg-color="" />
      <div class="head-filters-bar">
        <div class="item" @click="handleOpenFilter('sort')">排序<img class="icon" src="@/assets/icon-sort.png"></div>
        <!-- <div v-if="!!categoryId" class="item" @click="showFilterStyle=true">风格<img class="icon" src="@/assets/icon-style.png"></div> -->
        <div class="item" @click="handleOpenFilter('filter')">筛选<img class="icon" src="@/assets/icon-filter.png"></div>
      </div>
    </div>
    <div class="linearbg" :style="{'top':topHeight+'px'}">
      <div class="greybg" />
    </div>
    <div class="goods-list-content">
      <List
        ref="list"
        class="list-page-container"
        :set-page-size="10"
        :finished.sync="finished"
        :reset-fun="resetData"
        :load="load"
        :refresh="load"
      >
        <ShowWindow
          v-for="(g,i) in list"
          :key="i"
          is-product
          :name="g.productName"
          :price="g.price"
          :src="g.pic"
          :tag-list="getSellingPoints(g)"
          @click="clickHandle(g)"
        />
      </List>
    </div>
    <StyleFilterWindow
      v-if="!!categoryId"
      v-model="templateEv"
      :visiable.sync="showFilterStyle"
    />
    <OtherFilterWindow
      :visiable.sync="showOtherFilter"
      :filter-flag="filterFlag"
      @refresh="resetPageData"
    />
  </div>
</template>

<script>
import List from '@/components/PageList'
import ShowWindow from '@/components/ShowWindow'
import StyleFilterWindow from './components/StyleFilterWindow'
import OtherFilterWindow from './components/OtherFilterWindow'
import { gcenterProduct, getDefaultTemplateIdfunction } from '@/apis/search'
import { randomId } from '@/utils'
import { mapGetters, mapMutations } from 'vuex'
export default {
  name: 'GoodsList',
  components: { List, ShowWindow, StyleFilterWindow, OtherFilterWindow },
  data() {
    return {
      topHeight: 104, // 20+44+40
      pageTitle: this.$route.query.name,
      categoryId: this.$route.query.categoryId, // 当前品类(类目)
      templateEv: this.$route.query.sericesId, // 当前所选风格系列
      list: [],
      finished: false,
      defaultTemplateId: '',
      rawFilterData: [],
      attr_ev: '',
      showFilterStyle: false,
      showOtherFilter: false,
      filterFlag: 'filter'
    }
  },
  computed: {
    ...mapGetters('nav', ['filterData'])
  },
  watch: {
    templateEv(v) {
      this.$nextTick(() => {
        this.resetPageData()
      })
    }
  },
  created() {

  },
  activated() {
    this.updateFilterData(this.rawFilterData)
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        this.topHeight = this.$refs.top.offsetHeight
      }, 100)
    })
  },
  beforeDestroy() {
    this.updateFilterData([])
  },
  beforeRouteLeave(to, from, next) {
    if (to.name !== 'FinishedDetail') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  methods: {
    ...mapMutations('nav', ['updateFilterData']),
    async load(page, rows) {
      let defaultTemplateId = ''
      if (!this.defaultTemplateId) {
        await this.getTemplate()
        defaultTemplateId = this.defaultTemplateId
      } else {
        defaultTemplateId = this.defaultTemplateId
      }

      if (!defaultTemplateId) return Promise.reject('noError')

      const selectedData = this.$extrFilterData(this.filterData)
      const c1Ids = this.$extrFIlterValueByFlag(selectedData, /^c1@@@.*/, false)
      const c2Ids = this.$extrFIlterValueByFlag(selectedData, /^c2@@@.*/, false)
      const c3Ids = this.$extrFIlterValueByFlag(selectedData, /^c3@@@.*/, false)
      const c4Ids = this.$extrFIlterValueByFlag(selectedData, /^c4@@@.*/, false)
      let attr = this.$extrFIlterEvsValueByFlag(selectedData, /^attr@@@.*/, true, '@')
      // const templateEv = this.$extrFIlterEvsValueByFlag(selectedData, /^template_attr@@@.*/, true, '@')
      const productStates = this.$extrFIlterValueByFlag(selectedData, /^product_state@@@.*/, false)
      const purchaseHandles = this.$extrFIlterValueByFlag(selectedData, /^purchase_handle@@@.*/, false)
      const defaultCategoryIds = []
      let isDefaultFilterCondition = 'Y'

      if (selectedData.length > 0) {
        isDefaultFilterCondition = 'N'
      }

      let categoryIds = []
      if (this.categoryId) {
        categoryIds.push(this.categoryId)
      } else {
        categoryIds = this.$extrFIlterValueByFlag(selectedData, /^category@@@.*/, false)
      }

      if (this.attr_ev) {
        attr = [attr, this.attr_ev].filter(e => e).join('@')
      }

      let sort = this.$extrFIlterValueByFlag(selectedData, /^sort*/, false).join(',')

      const data = {
        page,
        rows,
        c1Ids,
        c2Ids,
        c3Ids,
        c4Ids,
        categoryIds,
        defaultCategoryIds,
        productStates,
        purchaseHandles,
        isDefaultFilterCondition,
        filterTemplateConditionId: defaultTemplateId,
        ev: attr,
        templateEv: this.templateEv
      }
      if (!sort) {
        sort = 'sort_ttm_desc'
      }
      if (sort && sort !== 'default') {
        data.sort = sort
      }

      const priceRange = this.filterData.find(v => v.flag === 'price')
      if (priceRange) {
        if (priceRange.rawValue1) {
          data.priceFrom = priceRange.rawValue1
        }
        if (priceRange.rawValue2) {
          data.priceTo = priceRange.rawValue2
        }
      }

      const dateRange = this.filterData.find(v => v.flag === 'ttm')
      if (dateRange) {
        if (dateRange.rawValue1) {
          data.ttmFrom = `${dateRange.rawValue1}`
        }
        if (dateRange.rawValue2) {
          data.ttmTo = `${dateRange.rawValue2}`
        }
      }

      return gcenterProduct(data).then(res => {
        const data = (res.data && res.data.remoteSolrProductGroupDTOS) || ''
        if (data) {
          if (data.records) {
            this.list.push(...data.records)
          }
        }

        if (!data || !(data.records && data.records.length) || (data.totalRows <= this.list.length)) {
          this.finished = true
        }
        if (!data) return
        // const excludeType = this.categoryId ? 'category' : 'template_attr'
        const filterData = res.data.filterData.filter(v => {
          if ((!v.items || v.items.length === 0)) {
            return false
          }
          if (this.categoryId) {
            return v.type !== 'category'
          } else {
            return v.name !== '风格'
          }
        })

        this.$concatFilterData(filterData, this.filterData)
        const sortPriceRaw = [
          {
            unId: randomId(),
            title: '排序',
            show: true,
            flag: 'sort',
            type: 'priceSort',
            multiple: false,
            isMultChoose: false,
            children: [
              { label: '默认排序', value: 'default', selected: !['sort_price_desc', 'sort_price_asc', 'sort_ttm_desc'].includes(sort) },
              { label: '新品优先', value: 'sort_ttm_desc', selected: sort === 'sort_ttm_desc' },
              // { label: '新品优先', value: 'sort_ttm_asc', selected: sort === 'sort_ttm_asc' }, // 上市时间从低到高
              { label: '价格从低到高', value: 'sort_price_asc', selected: sort === 'sort_price_asc' },
              { label: '价格从高到低', value: 'sort_price_desc', selected: sort === 'sort_price_desc' }
            ]
          },
          {
            uuId: randomId(),
            title: '价格范围',
            flag: 'price',
            show: false,
            type: 'textrange',
            selected: true,
            value1: priceRange?.rawValue1 || '',
            value2: priceRange?.rawValue2 || '',
            rawValue1: priceRange?.rawValue1 || '',
            rawValue2: priceRange?.rawValue2 || '',
            placeholder1: '最低价',
            placeholder2: '最高价',
            fieldType: 'number',
            formatter: (value) => {
              if (['', null, undefined].includes(value)) return ''
              var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
              if (!reg.test(value)) {
                this.$toast('金额格式不对')
                return ''
              }
              return value
            }
          },
          {
            uuId: randomId(),
            title: '上市日期',
            flag: 'ttm',
            show: false,
            type: 'monthrange',
            selected: true,
            value1: dateRange?.rawValue1 || '',
            value2: dateRange?.rawValue2 || '',
            rawValue1: dateRange?.rawValue1 || '',
            rawValue2: dateRange?.rawValue2 || '',
            placeholder1: '',
            placeholder2: ''
          }
        ]
        this.rawFilterData = [...sortPriceRaw, ...filterData]
        this.updateFilterData([...sortPriceRaw, ...filterData])
        // 处理默认项
        for (const f of filterData) {
          if (f.relevanceItemIndex && f.relevanceItemIndex.length > 0) {
            f.relevanceItemIndex.forEach(index => {
              const selected = f.children.some(e => e.selected)
              this.$store.commit('nav/updateRelevanceItemShow', { index, selected })
            })
          }
        }
      })
    },
    resetPageData() {
      if (this.$refs.list) {
        this.$refs.list.resetPageData()
      }
    },
    resetData() {
      this.list = []
    },
    // 获取默认模板
    async getTemplate() {
      return await getDefaultTemplateIdfunction().then(res => {
        this.defaultTemplateId = res.msg
        return res.msg
      })
    },
    handleOpenFilter(type) {
      this.filterFlag = type
      this.$nextTick(() => {
        this.showOtherFilter = true
      })
    },
    clickHandle(g) {
      this.$router.push({
        name: 'FinishedDetail',
        params: { spuId: g.productId, skuId: g.skuId }
      })
    },
    getSellingPoints(item) {
      const list = item.solrProductDTOS || []
      const obj = list.find(v => v.skuId === item.skuId)
      return (obj && obj.sellingPoints) || []
    }
  }
}

</script>
<style lang='less' scoped>
.goods-list-page-head{
  position: fixed;
  left: 0;
  top: 0;
  width:100%;
  z-index: 99;
  background: url(~@/assets/head-fill-con.png);
  background-position: left top;
  background-size: 100% auto;
  background-repeat: no-repeat;
}

.goods-list-page{
  min-height: 100vh;
  box-sizing: border-box;
  background: url(~@/assets/head-fill-con.png) #F5F6F7;
  background-position: left top;
  background-size: 100% auto;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
.head-filters-bar{
  padding: 10px 16px;
  height: 40px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .item{
    margin-left: 24px;
    height: 20px;
    line-height: 20px;
    color: #FFFFFF;
    font-size: 14px;
    font-weight: bold;
    display: flex;
    align-items: center;
    .icon{
      margin-left: 4px;
      width: 20px;
      height: 20px;
    }
  }
}
.linearbg{
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 48px;
  background: linear-gradient(360deg, #F2F4F5 0%, rgba(255,255,255,0) 100%);
  .greybg{
    position: relative;
    &::after{
      content: '';
      position: absolute;
      left: 0;
      top:48px;
      width: 100%;
      height: 100px;
      background: #F5F6F7;
    }
  }
}
.goods-list-content{
  position: relative;
  z-index: 2;
  /deep/.page-list{
    padding: 0 12px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    box-sizing: border-box;
    >*{
      margin-bottom: 16px;
      &:nth-child(odd){
        margin-right: 12px;
      }
    }
  }
}
.list-page-container{
  min-height: 50vh;
}

</style>
